package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName OrderServiceImpl
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/7/1 11:47
 * @Version V1.0
 **/
@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;


//    @Autowired
//    private OrderMapper orderMapper;

    @Autowired
    private OrderTccAction orderTccAction;

    @GlobalTransactional
    @Override
    public void create(Order order) {
        //生成订单id
        String s= easyIdClient.nextId("order_business");
        //包装类Long
        Long orderId = Long.valueOf(s);

        order.setId(orderId);
        //不再执行业务操作存储订单
        //而是改用调用TCC第一阶段方法,冻结订单,预留订单

       // orderMapper.create(order);
        /*
         orderTccAction是一个动态代理对象,用AOP添加了通知代码
         在通知代码中,创建了上下文对象,并传递到代理的目标方法中
        */
        orderTccAction.prepare(
                null,
                order.getId(),
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());

        //远程调用账户扣减账户金额
accountClient.decrease(order.getUserId(), order.getMoney());

        //远程调用库存减少商品库存
storageClient.decrease(order.getProductId(), order.getCount());

    }
}
